import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'
import {
	reqLogin
} from '../api/login.api.js'


export const useLoginStore = defineStore(
	'login',
	() => {
		// 输入的用户信息
		const userinfo = ref({
			username: '',
			password: ''
		})

		const Token = ref('')
		const RefreshToken = ref('')
		const UserInfo = ref({})
		
		// 跳转登录
		const goLogin = (url) => {
			uni.navigateTo({
				url: `/pages/login/login?url=${url}`
			})
		}
		
		// 跳转设置
		const goSetting = () => {
			uni.navigateTo({
				url: '/pages/setting/setting'
			})
		}

		// 登录
		const login = async (data) => {
			let {
				status,
				message,
				token,
				refreshToken,
				userInfo
			} = await reqLogin(data)
			if (status === 0) {
				Token.value = token
				RefreshToken.value = refreshToken
				UserInfo.value = userInfo
				// 跳转主页
				uni.switchTab({
					url: '/pages/user/user'
				})
				// 清空输入框
				userinfo.value = {
					username: '',
					password: ''
				}
			} else {
				uni.showToast({
					title: message,
					icon: 'error'
				})
			}
			
		}

        // 退出登录
		const logOut = () => {
			Token.value = ''
			RefreshToken.value = ''
			UserInfo.value = {}
			uni.switchTab({
				url: '/pages/user/user'
			})
		}

		return {
			userinfo,
			login,
			Token,
			RefreshToken,
			UserInfo,
			goLogin,
			goSetting,
			logOut
			
		}
	}, {
		persist: {
			storage: {
				getItem(key) {
					return JSON.parse(uni.getStorageSync(key)); // 手动替代 destr
				},
				setItem(key, value) {
					uni.setStorageSync(key, JSON.stringify(value));
				},
			},
		}
	}
)